<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class CarRecord extends Model
{
    use HasFactory;

    protected $fillable = [
        'openid', 'use_date', 'car_type', 'car_model', 'driver_name',
        'license_plate', 'dispatcher_id', 'passenger_name', 'start_time',
        'end_time', 'mileage', 'base_price', 'work_hour_limit', 'km_limit',
        'overtime_fee_per_hour', 'over_km_fee', 'parking_fee', 'parking_fee_included',
        'toll_fee', 'toll_fee_included', 'accommodation_fee', 'accommodation_fee_included',
        'fuel_fee', 'fuel_fee_included', 'meal_fee', 'meal_fee_included',
        'car_wash_fee', 'car_wash_fee_included', 'water_fee', 'water_fee_included',
        'other_fee', 'other_fee_included', 'route_description', 'total_amount'
    ];

    protected $casts = [
        'use_date' => 'date',
        'start_time' => 'datetime:H:i',
        'end_time' => 'datetime:H:i',
        'mileage' => 'decimal:2',
        'base_price' => 'decimal:2',
        'km_limit' => 'decimal:2',
        'overtime_fee_per_hour' => 'decimal:2',
        'over_km_fee' => 'decimal:2',
        'parking_fee' => 'decimal:2',
        'parking_fee_included' => 'boolean',
        'toll_fee' => 'decimal:2',
        'toll_fee_included' => 'boolean',
        'accommodation_fee' => 'decimal:2',
        'accommodation_fee_included' => 'boolean',
        'fuel_fee' => 'decimal:2',
        'fuel_fee_included' => 'boolean',
        'meal_fee' => 'decimal:2',
        'meal_fee_included' => 'boolean',
        'car_wash_fee' => 'decimal:2',
        'car_wash_fee_included' => 'boolean',
        'water_fee' => 'decimal:2',
        'water_fee_included' => 'boolean',
        'other_fee' => 'decimal:2',
        'other_fee_included' => 'boolean',
        'total_amount' => 'decimal:2'
    ];

    public function dispatcher()
    {
        return $this->belongsTo(Dispatcher::class);
    }

    // 计算总金额
    public function calculateTotal()
    {
        $total = $this->base_price;
        
        // 添加实报费用
        if ($this->parking_fee_included) $total += $this->parking_fee;
        if ($this->toll_fee_included) $total += $this->toll_fee;
        if ($this->accommodation_fee_included) $total += $this->accommodation_fee;
        if ($this->fuel_fee_included) $total += $this->fuel_fee;
        if ($this->meal_fee_included) $total += $this->meal_fee;
        if ($this->car_wash_fee_included) $total += $this->car_wash_fee;
        if ($this->water_fee_included) $total += $this->water_fee;
        if ($this->other_fee_included) $total += $this->other_fee;
        
        return $total;
    }
}
